package com.ruoyi.system;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.ruoyi.system.domain.PmsBrand;
import com.ruoyi.system.service.IPmsBrandService;

import java.util.ArrayList;
import java.util.List;

public class PmsBrandImportListener extends AnalysisEventListener<PmsBrand> {

    private final IPmsBrandService pmsBrandService;
    private final List<PmsBrand> cachedDataList = new ArrayList<>();

    public PmsBrandImportListener(IPmsBrandService pmsBrandService) {
        this.pmsBrandService = pmsBrandService;
    }

    @Override
    public void invoke(PmsBrand data, AnalysisContext context) {
        cachedDataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!cachedDataList.isEmpty()) {
            for (PmsBrand brand : cachedDataList) {
                pmsBrandService.insertPmsBrand(brand);
            }
        }
    }
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException ex = (ExcelDataConvertException) exception;
            throw new RuntimeException(String.format("第%d行，第%d列数据格式错误",
                    ex.getRowIndex() + 1, ex.getColumnIndex() + 1));
        } else {
            throw exception;
        }
    }
}